//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System.Reflection;
using System.IO;
using Microsoft.Research.DataLayer;
using System;
namespace Microsoft.Research.ActivitiesSyncLibrary
{
    partial class ActivitySyncInstaller
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        private static string libraryPath = String.Empty;

        
        private const string UserName = @"UserName";
        private const string DomainName = @"DomainName";

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
        }
        /// <summary>
        /// This method syncs all the libraries in the path\libraries to registry
        /// </summary>
        /// <param name="stateSaver"></param>
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            try
            {                
                Assembly me = Assembly.GetExecutingAssembly();
                string myPath = Path.GetDirectoryName(me.Location);

                //Put the alternate location
                ConnectionManager.AlternateProviderLocation = myPath;
                //Initialize connection manager
                SR_Connection.Init();

                ConnectionManager cmgr = ConnectionManager.Create(ConnectionManager.CancelBehavior.ThrowException);
                Connection registryConn = cmgr.PickConnection(ConnectionManagerBase.ConnectionUI.NeverShowUI);

                ResolveEventHandler resolveHandler = new ResolveEventHandler(CurrentDomain_AssemblyResolve);
                AppDomain.CurrentDomain.AssemblyResolve += resolveHandler;

                //do the actual sync
                SyncActivites syncToRegistry = new SyncActivites(registryConn);
                libraryPath = Path.Combine(myPath, "Libraries");

                string userName = Context.Parameters[UserName].ToString();
                string domainName = Context.Parameters[DomainName].ToString();                

                syncToRegistry.IntializeUserRoles(registryConn, userName, domainName);

                //Sync the folder
                syncToRegistry.SyncActivitiesToRegistry(myPath);

                base.Install(stateSaver);
            }
            catch (Exception exp)
            {
                Context.LogMessage(exp.Message);
                Context.LogMessage(exp.StackTrace);
                if (null != exp.InnerException)
                {
                    Context.LogMessage(exp.InnerException.Message);
                    Context.LogMessage(exp.InnerException.StackTrace);
                }
                throw exp;
            }
        }

        static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            string asmFilePath = args.Name;
            string asmFile = Path.GetFileName(asmFilePath);

            try
            {
                //In case of assembly info create the dll name and try to load it from the current dir
                //if not try it with the AlternateProviderLocation which will be set from GetProviders()
                //If we receive an actual path split will return only 1 string
                string[] strAssembly = asmFilePath.Split(',');
                if (strAssembly.Length > 1 && !string.IsNullOrEmpty(strAssembly[0]))
                {
                    asmFile = string.Format("{0}.dll", strAssembly[0]);
                }

                Assembly try1 = Assembly.LoadFile(asmFilePath);
                return try1;
            }
            catch
            {
                if (!string.IsNullOrEmpty(libraryPath))
                {
                    string asmCandidate = Path.Combine(libraryPath, asmFile);

                    if (File.Exists(asmCandidate))
                    {
                        return Assembly.LoadFile(asmCandidate);
                    }
                }
            }
            return null;
        }


        #endregion
    }
}